<template>
  <div class="sales-trend-chart">
    <div class="chart-header">
      <h3 class="chart-title">销售趋势</h3>
      <div class="range-selector">
        <button 
          v-for="range in ranges" 
          :key="range.value" 
          @click="setRange(range.value)"
          :class="{ active: selectedRange === range.value }"
        >
          {{ range.label }}
        </button>
      </div>
    </div>
    
    <BaseChart
      v-if="trendData.length > 0"
      type="area"
      height="300px"
      :series="chartSeries"
      :categories="chartCategories"
      xAxisTitle="日期"
      yAxisTitle="销售额 (USDT)"
      :showLegend="true"
      :showTooltip="true"
      :smooth="true"
      :enableZoom="false"
      :customOptions="chartOptions"
    />
    
    <div class="chart-summary" v-if="trendData.length > 0">
      <div class="summary-item">
        <div class="summary-label">总销售额</div>
        <div class="summary-value">{{ totalSales.toLocaleString() }} USDT</div>
      </div>
      <div class="summary-item">
        <div class="summary-label">总订单数</div>
        <div class="summary-value">{{ totalOrders.toLocaleString() }}</div>
      </div>
      <div class="summary-item">
        <div class="summary-label">平均客单价</div>
        <div class="summary-value">{{ averageOrderValue.toLocaleString() }} USDT</div>
      </div>
      <div class="summary-item" :class="totalGrowthClass">
        <div class="summary-label">同比增长</div>
        <div class="summary-value">{{ totalGrowth }}%</div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onBeforeUnmount } from 'vue';
import BaseChart from './BaseChart.vue';
import { generateSalesTrendData } from '@/utils/adminMock';

// 可选的时间范围
const ranges = [
  { label: '7天', value: 7 },
  { label: '30天', value: 30 },
  { label: '90天', value: 90 }
];

// 默认选择的时间范围
const selectedRange = ref(7);

// 销售趋势数据
const trendData = ref(generateSalesTrendData(selectedRange.value));

// 设置时间范围
const setRange = (days: number) => {
  selectedRange.value = days;
  trendData.value = generateSalesTrendData(days);
};

// 图表数据系列
const chartSeries = computed(() => {
  if (!trendData.value || trendData.value.length === 0) {
    return [];
  }
  
  return [
    {
      name: '销售额',
      data: trendData.value.map(item => item.sales),
      type: 'area'
    },
    {
      name: '订单数',
      data: trendData.value.map(item => item.orders),
      type: 'line'
    }
  ];
});

// 图表分类（X轴标签）
const chartCategories = computed(() => 
  trendData.value.map(item => item.date)
);

// 图表自定义选项
const chartOptions = computed(() => ({
  fill: {
    type: 'gradient',
    gradient: {
      shade: 'light',
      type: 'vertical',
      shadeIntensity: 0.3,
      opacityFrom: 0.7,
      opacityTo: 0.2,
      stops: [0, 100]
    }
  },
  stroke: {
    width: [2, 2],
    curve: 'smooth'
  },
  colors: ['#5e72e4', '#2dce89'],
  yaxis: [
    {
      title: {
        text: '销售额 (USDT)'
      },
      labels: {
        formatter: (value: number) => `${value.toLocaleString()}`
      }
    },
    {
      opposite: true,
      title: {
        text: '订单数'
      },
      labels: {
        formatter: (value: number) => `${value.toLocaleString()}`
      }
    }
  ],
  tooltip: {
    y: {
      formatter: (val: number, opts: any) => {
        return opts.seriesIndex === 0 
          ? `${val.toLocaleString()} USDT` 
          : `${val.toLocaleString()} 订单`;
      }
    },
    shared: true,
    intersect: false
  },
  dataLabels: {
    enabled: false
  },
  markers: {
    size: 3,
    hover: {
      size: 5
    }
  }
}));

// 计算总销售额
const totalSales = computed(() => 
  trendData.value.reduce((sum, item) => sum + item.sales, 0)
);

// 计算总订单数
const totalOrders = computed(() => 
  trendData.value.reduce((sum, item) => sum + item.orders, 0)
);

// 计算平均客单价
const averageOrderValue = computed(() => 
  totalOrders.value > 0 
    ? Math.round(totalSales.value / totalOrders.value) 
    : 0
);

// 计算总体同比增长率
const totalGrowth = computed(() => {
  if (trendData.value.length === 0) return 0;
  
  const currentTotal = trendData.value.reduce((sum, item) => sum + item.sales, 0);
  const lastYearTotal = trendData.value.reduce((sum, item) => sum + (item.lastYearSales || 0), 0);
  
  if (lastYearTotal === 0) return 0;
  
  return ((currentTotal - lastYearTotal) / lastYearTotal * 100).toFixed(2);
});

// 总增长率的CSS类
const totalGrowthClass = computed(() => {
  const growth = parseFloat(totalGrowth.value);
  if (growth > 0) return 'positive-growth';
  if (growth < 0) return 'negative-growth';
  return '';
});

// 组件挂载时获取数据
onMounted(() => {
  trendData.value = generateSalesTrendData(selectedRange.value);
});

// 组件卸载前清理数据
onBeforeUnmount(() => {
  trendData.value = [];
});
</script>

<style scoped>
.sales-trend-chart {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  padding: 20px;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.chart-title {
  font-size: 16px;
  font-weight: 600;
  margin: 0;
  color: #333;
}

.range-selector {
  display: flex;
  gap: 8px;
}

.range-selector button {
  background-color: #f8f9fa;
  border: 1px solid #e2e8f0;
  border-radius: 4px;
  padding: 6px 12px;
  font-size: 13px;
  cursor: pointer;
  transition: all 0.2s;
}

.range-selector button.active {
  background-color: #5e72e4;
  color: white;
  border-color: #5e72e4;
}

.range-selector button:hover:not(.active) {
  background-color: #edf2f7;
}

.chart-summary {
  display: flex;
  margin-top: 20px;
  gap: 20px;
  flex-wrap: wrap;
}

.summary-item {
  flex: 1;
  min-width: 150px;
  background-color: #f8f9fa;
  border-radius: 6px;
  padding: 12px;
}

.summary-label {
  font-size: 12px;
  color: #718096;
  margin-bottom: 4px;
}

.summary-value {
  font-size: 16px;
  font-weight: 600;
  color: #2d3748;
}

.positive-growth .summary-value {
  color: #2dce89;
}

.negative-growth .summary-value {
  color: #f5365c;
}
</style> 
 